#include"SeqList.h"

void SLInit(SL* ps)
{
	ps->a = (SLDateType*)malloc(sizeof(SLDateType)*4);
	if (ps->a == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	ps->capacity = 4;
	ps->size = 0;
}

void SLDestory(SL*ps)
{
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->size = 0;
}
void SLPrint(SL* ps)
{
	SLDateType i = 0;
	for (i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
}

void SLCheckCapacity(SL* ps)
{
	if (ps->capacity == ps->size)
	{
		SLDateType* tmp = (SLDateType*)realloc(ps->a, ps->capacity * 2 * sizeof(SLDateType));
		if (tmp == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = ps->capacity * 2;
	}
}


void SLPushBack(SL * ps, int x)
{
	SLCheckCapacity(ps);
	ps->a[ps->size] = x;
	ps->size++;
}


void SLPopBack(SL* ps)
{
	assert(ps->size > 0);
	ps->size--;
}

void SLPushfront(SL* ps, SLDateType x)
{
	SLCheckCapacity(ps);
	SLDateType end = ps->size - 1;
	while (end >= 0)
	{
		ps->a[end+1] = ps->a[end];
		--end;
	}
	ps->a[0] = x;
	ps->size++;
	
}

void SLPopfront(SL* ps)
{
	for (int i = 1; i < ps->size; i++)
	{
		ps->a[i-1] = ps->a[i];
	}
	ps->size--;
}

int SLFind(SL* ps, int x)
{
	int pos = 0;
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			pos = i;
			return i;
		}
	}
    return -1;
}


void SLInsert(SL* ps, int pos, int x)
{
	assert(pos >= 0 && pos <= ps->size);
	SLDateType end = ps->size-1;
	SLCheckCapacity(ps);
	while(end >=pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[pos] = x;
	ps->size++;

}


void SLErase(SL* ps, int pos)
{
	assert(pos >= 0 && pos < ps->size);
	SLDateType start = pos + 1;
	while (start<ps->size)
	{
		ps->a[start - 1] = ps->a[start];
		start++;
	}
	ps->size--;
}